package cn.ly.core.concurrent;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorServiceTest {
	
	public static void main(String[] args) {
		final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(2);
		final Runnable beeper = new Runnable(){
		int count = 0;
			public void run() {
				System.out.println(new Date() + " beep " + (++count));
			}
		};
		//延迟1秒运行，每个2秒执行一次
		final ScheduledFuture beeperHandler = 
				scheduled.scheduleAtFixedRate(beeper, 1, 2, TimeUnit.SECONDS);
		//2秒钟后运行，并每次在上次任务运行完后等待5秒后重新运行
		final ScheduledFuture beeperHandler2 = 
				scheduled.scheduleWithFixedDelay(beeper, 2, 5, TimeUnit.SECONDS);
		//30秒后结束关闭任务，并且关闭Scheduler
		scheduled.schedule(new Runnable(){
			public void run(){
				beeperHandler.cancel(true);
				beeperHandler2.cancel(true);
				scheduled.shutdown();
			}
		}, 30, TimeUnit.SECONDS);
		
	}
}
